package com.chaodev.base.controller;

import com.alibaba.fastjson.JSON;
import com.chaodev.base.base.RedisDao;
import com.chaodev.base.model.Result;
import com.chaodev.base.model.ResultEnum;
import com.chaodev.base.model.UserInfo;
import com.chaodev.base.service.IFileService;
import com.chaodev.base.service.ILogService;
import com.chaodev.base.utils.JwtUtil;
import io.minio.*;
import io.minio.http.Method;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.cxf.helpers.IOUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 文件上传下载相关
 *
 * @author cp
 * @date 2022/1/21 10:40
 **/
@RestController
@RequestMapping(value = "upload")
@Api(value = "文件上传下载相关")
public class UploadController {

    @Autowired
    private RedisDao redisDao;

    @Autowired
    private ILogService logService;

    @Resource
    private MinioClient minioClient;

    @Autowired
    private IFileService fileService;

    @Value("${variables.importProtectTime}")
    private int daysBefore;

    @Value("${variables.importSaveType}")
    private String importSaveType;

    @Value("${variables.importSavePath}")
    private String importSavePath;
    /**
     * 文件类型
     */
    private static final List<String> FILE_TYPE = Arrays.asList("csv","jpg", "jpe", "jpeg", "png", "gif", "txt", "pdf", "docx", "doc", "xlsx", "xls", "zip", "rar", "ppt", "pptx","mp4", "mov", "m4v", "avi", "dat", "mkv", "flv", "vob", "rm", "rmvb", "wmv", "asf", "asx", "tif", "tiff", "ico", "bmp", "dib");

    /**
     * minio存储桶名称(起名请参照minio命名存储桶规则，否则无法创建存储桶及进行其他操作)
     */
    private static final String BUCKET_NAME = "test20220124";

    /**
     * 桶占位符
     */
    private static final String BUCKET_PARAM = "${bucket}";
    /**
     * bucket权限-只读
     */
    private static final String READ_ONLY = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetBucketLocation\",\"s3:ListBucket\"],\"Resource\":[\"arn:aws:s3:::" + BUCKET_PARAM + "\"]},{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetObject\"],\"Resource\":[\"arn:aws:s3:::" + BUCKET_PARAM + "/*\"]}]}";
    /**
     * bucket权限-只写
     */
    private static final String WRITE_ONLY = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetBucketLocation\",\"s3:ListBucketMultipartUploads\"],\"Resource\":[\"arn:aws:s3:::" + BUCKET_PARAM + "\"]},{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:AbortMultipartUpload\",\"s3:DeleteObject\",\"s3:ListMultipartUploadParts\",\"s3:PutObject\"],\"Resource\":[\"arn:aws:s3:::" + BUCKET_PARAM + "/*\"]}]}";
    /**
     * bucket权限-读写
     */
    private static final String READ_WRITE = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetBucketLocation\",\"s3:ListBucket\",\"s3:ListBucketMultipartUploads\"],\"Resource\":[\"arn:aws:s3:::" + BUCKET_PARAM + "\"]},{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:DeleteObject\",\"s3:GetObject\",\"s3:ListMultipartUploadParts\",\"s3:PutObject\",\"s3:AbortMultipartUpload\"],\"Resource\":[\"arn:aws:s3:::" + BUCKET_PARAM + "/*\"]}]}";

    /**
     * 文件夹上传路径
     */
    @Value("${upload.path}")
    private String FILE_PATH ;

    /**
     * ftp相关配置
     */
    @Value("${ftp.url}")
    private String ftpUrl;
    @Value("${ftp.port}")
    private String ftpPort;
    @Value("${ftp.userName}")
    private String ftpUserName;
    @Value("${ftp.password}")
    private String ftpPassword;

    /**
     * minio文件上传
     *
     * @param fileArr 文件数组
     * @param request
     * @return com.kmvc.vcbase.model.Result
     * @author cp
     * @date 2022/1/24 13:56
     **/
    @PostMapping(value = "minioUpload")
    @ApiOperation("minio文件上传")
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result minioUpload(MultipartFile[] fileArr, HttpServletRequest request) {
        Result result = new Result();
        //校验文件数组是否为空
        if (null == fileArr || fileArr.length == 0) {
            result.setCode(ResultEnum.FORBIDDEN.getCode());
            result.setMsg("上传文件列表为空，请核实后重试！");
            return result;
        }
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        try {
            if (redisDao.existsKey(token)) {
                userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
                //判断上传的文件是否合法
                List<String> illegalFileList = new ArrayList<>();
                List<String> failFileList = new ArrayList<>();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                List<Map<String, Object>> fileList = new ArrayList<>(fileArr.length);
                Map<String, Object> map;
                for (MultipartFile file : fileArr) {
                    String orgFileName = file.getOriginalFilename();
                    String saveFileName = sdf.format(new Date()) + "/" + getUuidFileName(orgFileName);
                    //判断文件名是否为空以及后缀名是否合法
                    if (null == orgFileName || "".equals(orgFileName) || !FILE_TYPE.contains(getExtName(orgFileName))) {
                        illegalFileList.add(orgFileName);
                        continue;
                    }
                    //判断存储桶是否存在，不存在即创建
                    if (!bucketExists(BUCKET_NAME)) {
                        //创建存储桶
                        if (makeBucket(BUCKET_NAME)) {
                            //设置存储桶策略为读写
                            setBucketPolicy(BUCKET_NAME, "read-write");
                        }
                    }
                    //存储文件
                    if (!upload(file, saveFileName, BUCKET_NAME)) {
                        failFileList.add(orgFileName);
                        continue;
                    }
                    map = new HashMap<>(3);
                    //文件原名称
                    map.put("originalFileName", orgFileName);
                    //文件的存储名称
                    map.put("saveFileName", saveFileName);
                    fileList.add(map);
                }
                if (illegalFileList.size() > 0 || failFileList.size() > 0) {
                    StringBuilder msg = new StringBuilder("下列文件未上传成功：");
                    if (illegalFileList.size() > 0) {
                        msg.append("{[失败原因：文件名不合法]").append(JSON.toJSONString(illegalFileList)).append("};");
                    }
                    if (failFileList.size() > 0) {
                        msg.append("{[失败原因：上传文件发生错误]").append(JSON.toJSONString(failFileList)).append("};");
                    }
                    result.setCode(-1);
                    result.setMsg(msg.toString());
                    return result;
                }
                result.setCode(0);
                result.setMsg("上传成功");
                result.setData(fileList);
                return result;
            } else {
                result.setCode(-1);
                result.setMsg("登录超时");
                return result;
            }
        } catch (Exception e) {
            result.setCode(-1);
            result.setMsg("发生错误:" + e.getMessage());
            return result;
        } finally {
            Result logResult = new Result();
            //日志结果只做标识，不记录返回数据
            BeanUtils.copyProperties(result, logResult);
            logResult.setData(null);
            String resultCode = logResult.getCode() == 0 ? "SUCCESS" : "ERROR";
            logService.logAdd("", "minio文件上传", resultCode, logResult.toString(), userInfo, request);
        }
    }


    /**
     * minio文件上传(支持uniapp批量上传,文件的键不可以能相同，否之不能取到全部文件)
     *
     * @param request
     * @return com.kmvc.vcbase.model.Result
     * @author cp
     * @date 2022/1/24 13:56
     **/
    @PostMapping(value = "minioMultiUpload")
    @ApiOperation("minio文件上传")
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result minioMultiUpload(HttpServletRequest request) {
        Result result = new Result();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> multipartFileMap = multipartRequest.getFileMap();
        List<MultipartFile> fileArr = new ArrayList<MultipartFile>(multipartFileMap.values());
        //校验文件数组是否为空
        if (null == fileArr || fileArr.size() == 0) {
            result.setCode(ResultEnum.FORBIDDEN.getCode());
            result.setMsg("上传文件列表为空，请核实后重试！");
            return result;
        }
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        try {
            if (redisDao.existsKey(token)) {
                userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
                //判断上传的文件是否合法
                List<String> illegalFileList = new ArrayList<>();
                List<String> failFileList = new ArrayList<>();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                List<Map<String, Object>> fileList = new ArrayList<>(fileArr.size());
                Map<String, Object> map;
                for (MultipartFile file : fileArr) {
                    String orgFileName = file.getOriginalFilename();
                    String saveFileName = sdf.format(new Date()) + "/" + getUuidFileName(orgFileName);
                    //判断文件名是否为空以及后缀名是否合法
                    if (null == orgFileName || "".equals(orgFileName) || !FILE_TYPE.contains(getExtName(orgFileName))) {
                        illegalFileList.add(orgFileName);
                        continue;
                    }
                    //判断存储桶是否存在，不存在即创建
                    if (!bucketExists(BUCKET_NAME)) {
                        //创建存储桶
                        if (makeBucket(BUCKET_NAME)) {
                            //设置存储桶策略为读写
                            setBucketPolicy(BUCKET_NAME, "read-write");
                        }
                    }
                    //存储文件
                    if (!upload(file, saveFileName, BUCKET_NAME)) {
                        failFileList.add(orgFileName);
                        continue;
                    }
                    map = new HashMap<>(3);
                    //文件原名称
                    map.put("originalFileName", orgFileName);
                    //文件的存储名称
                    map.put("saveFileName", saveFileName);
                    fileList.add(map);
                }
                if (illegalFileList.size() > 0 || failFileList.size() > 0) {
                    StringBuilder msg = new StringBuilder("下列文件未上传成功：");
                    if (illegalFileList.size() > 0) {
                        msg.append("{[失败原因：文件名不合法]").append(JSON.toJSONString(illegalFileList)).append("};");
                    }
                    if (failFileList.size() > 0) {
                        msg.append("{[失败原因：上传文件发生错误]").append(JSON.toJSONString(failFileList)).append("};");
                    }
                    result.setCode(-1);
                    result.setMsg(msg.toString());
                    return result;
                }
                result.setCode(0);
                result.setMsg("上传成功");
                result.setData(fileList);
                return result;
            } else {
                result.setCode(-1);
                result.setMsg("登录超时");
                return result;
            }
        } catch (Exception e) {
            result.setCode(-1);
            result.setMsg("发生错误:" + e.getMessage());
            return result;
        } finally {
            Result logResult = new Result();
            //日志结果只做标识，不记录返回数据
            BeanUtils.copyProperties(result, logResult);
            logResult.setData(null);
            String resultCode = logResult.getCode() == 0 ? "SUCCESS" : "ERROR";
            logService.logAdd("", "minio文件上传", resultCode, logResult.toString(), userInfo, request);
        }
    }


    /**
     * minio下载文件
     *
     * @param originalFileName 文件原名称
     * @param saveFileName     文件保存名称
     * @return com.kmvc.vcbase.model.Result
     * @author cp
     * @date 2022/1/25 9:58
     **/
    @GetMapping(value = "minioDownload")
    @ApiOperation("minio文件下载")
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result minioDownload(String originalFileName, String saveFileName, HttpServletRequest request, HttpServletResponse response) {
        Result result = new Result();
        //校验文件数组是否为空
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        InputStream in = null;
        try {
            if (redisDao.existsKey(token)) {
                userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
                //参数校验
                if (null == originalFileName || "".equals(originalFileName) || null == saveFileName || "".equals(saveFileName)) {
                    throw new Exception("参数校验不通过");
                }
                StatObjectResponse stat = getObjectInfo(BUCKET_NAME, saveFileName);
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(originalFileName, "UTF-8"));
                response.setContentType(stat.contentType());
                response.setCharacterEncoding("UTF-8");
                in = download(BUCKET_NAME, saveFileName);
                IOUtils.copy(in, response.getOutputStream());
                return null;
            } else {
                result.setCode(-1);
                result.setMsg("登录超时");
                return result;
            }
        } catch (Exception e) {
            result.setCode(-1);
            result.setMsg("发生错误:" + e.getMessage());
            return result;
        } finally {
            Result logResult = new Result();
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    result.setMsg(result.getMsg().concat("关闭InputStream失败！"));
                }
            }
            //日志结果只做标识，不记录返回数据
            BeanUtils.copyProperties(result, logResult);
            logResult.setData(null);
            String resultCode = logResult.getCode() == 0 ? "SUCCESS" : "ERROR";
            logService.logAdd("", "minio文件上传", resultCode, logResult.toString(), userInfo, request);
        }
    }

    /**
     * 文件夹文件上传
     *
     * @param fileArr
     * @return com.kmvc.vcbase.model.Result
     * @author cp
     * @date 2022/1/25 13:49
     **/
    @PostMapping("folderUpload")
    @ApiOperation("文件夹文件上传")
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result folderUpload(MultipartFile[] fileArr, HttpServletRequest request) {
        Result result = new Result();
        //校验文件数组是否为空
        if (null == fileArr || fileArr.length == 0) {
            result.setCode(ResultEnum.FORBIDDEN.getCode());
            result.setMsg("上传文件列表为空，请核实后重试！");
            return result;
        }
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        try {
            if (redisDao.existsKey(token)) {
                userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
                //判断上传的文件是否合法
                List<String> illegalFileList = new ArrayList<>();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                List<Map<String, Object>> fileList = new ArrayList<>(fileArr.length);
                Map<String, Object> map;
                for (MultipartFile file : fileArr) {
                    String orgFileName = file.getOriginalFilename();
                    String saveFileName = sdf.format(new Date()) + "/" + getUuidFileName(orgFileName);
                    //判断文件名是否为空以及后缀名是否合法
                    if (null == orgFileName || "".equals(orgFileName) || !FILE_TYPE.contains(getExtName(orgFileName))) {
                        illegalFileList.add(orgFileName);
                        continue;
                    }
                    //判断文件夹是否存在，不存在即创建
                    String savePath = FILE_PATH;
                    File folder = new File(savePath);
                    if (!folder.exists()) {
                        folder.mkdirs();
                    }
                    //保存文件
                    File saveFile = new File(savePath, saveFileName);
                    //复制
                    FileUtils.copyInputStreamToFile(file.getInputStream(), saveFile);
                    map = new HashMap<>(3);
                    //文件原名称
                    map.put("originalFileName", orgFileName);
                    //文件的存储名称
                    map.put("saveFileName", saveFileName);
                    fileList.add(map);
                }
                if (illegalFileList.size() > 0) {
                    result.setCode(-1);
                    result.setMsg("下列文件未上传成功：" + "{[失败原因：文件名不合法]" + JSON.toJSONString(illegalFileList) + "};");
                    return result;
                }
                result.setCode(0);
                result.setMsg("上传成功");
                result.setData(fileList);
            } else {
                result.setCode(-1);
                result.setMsg("登录超时");
            }
            return result;
        } catch (Exception e) {
            result.setCode(-1);
            result.setMsg("发生错误:" + e.getMessage());
            return result;
        } finally {
            Result logResult = new Result();
            //日志结果只做标识，不记录返回数据
            BeanUtils.copyProperties(result, logResult);
            logResult.setData(null);
            String resultCode = logResult.getCode() == 0 ? "SUCCESS" : "ERROR";
            logService.logAdd("", "文件夹文件上传", resultCode, logResult.toString(), userInfo, request);
        }
    }

    /**
     * 文件夹文件上传(支持uniapp批量上传,文件的键不可以能相同，否之不能取到全部文件)
     *
     * @return com.kmvc.vcbase.model.Result
     * @author cp
     * @date 2022/1/25 13:49
     **/
    @PostMapping("folderMultiUpload")
    @ApiOperation("文件夹文件上传")
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result folderMultiUpload(HttpServletRequest request) {
        Result result = new Result();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> multipartFileMap = multipartRequest.getFileMap();
        List<MultipartFile> fileArr = new ArrayList<MultipartFile>(multipartFileMap.values());
        //校验文件数组是否为空
        if (null == fileArr || fileArr.size() == 0) {
            result.setCode(ResultEnum.FORBIDDEN.getCode());
            result.setMsg("上传文件列表为空，请核实后重试！");
            return result;
        }
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        try {
            if (redisDao.existsKey(token)) {
                userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
                //判断上传的文件是否合法
                List<String> illegalFileList = new ArrayList<>();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                List<Map<String, Object>> fileList = new ArrayList<>(fileArr.size());
                Map<String, Object> map;
                for (MultipartFile file : fileArr) {
                    String orgFileName = file.getOriginalFilename();
                    String saveFileName = sdf.format(new Date()) + "/" + getUuidFileName(orgFileName);
                    //判断文件名是否为空以及后缀名是否合法
                    if (null == orgFileName || "".equals(orgFileName) || !FILE_TYPE.contains(getExtName(orgFileName))) {
                        illegalFileList.add(orgFileName);
                        continue;
                    }
                    //判断文件夹是否存在，不存在即创建
                    String savePath = FILE_PATH;
                    File folder = new File(savePath);
                    if (!folder.exists()) {
                        folder.mkdirs();
                    }
                    //保存文件
                    File saveFile = new File(savePath, saveFileName);
                    //复制
                    FileUtils.copyInputStreamToFile(file.getInputStream(), saveFile);
                    map = new HashMap<>(3);
                    //文件原名称
                    map.put("originalFileName", orgFileName);
                    //文件的存储名称
                    map.put("saveFileName", saveFileName);
                    fileList.add(map);
                }
                if (illegalFileList.size() > 0) {
                    result.setCode(-1);
                    result.setMsg("下列文件未上传成功：" + "{[失败原因：文件名不合法]" + JSON.toJSONString(illegalFileList) + "};");
                    return result;
                }
                result.setCode(0);
                result.setMsg("上传成功");
                result.setData(fileList);
            } else {
                result.setCode(-1);
                result.setMsg("登录超时");
            }
            return result;
        } catch (Exception e) {
            result.setCode(-1);
            result.setMsg("发生错误:" + e.getMessage());
            return result;
        } finally {
            Result logResult = new Result();
            //日志结果只做标识，不记录返回数据
            BeanUtils.copyProperties(result, logResult);
            logResult.setData(null);
            String resultCode = logResult.getCode() == 0 ? "SUCCESS" : "ERROR";
            logService.logAdd("", "minio文件上传", resultCode, logResult.toString(), userInfo, request);
        }
    }

    public boolean folderUpload1(MultipartFile[] fileArr, UserInfo userInfo, String uuid) {
        //校验文件数组是否为空
        if (null == fileArr || fileArr.length == 0) {
            return false;
        }
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            Map<String, Object> map;
            for (MultipartFile file : fileArr) {
                String orgFileName = file.getOriginalFilename();
                String saveFileName = sdf.format(new Date()) + "/" + uuid + "." + getExtName(file.getOriginalFilename());
                //判断文件夹是否存在，不存在即创建
                String savePath = importSavePath;
                File folder = new File(savePath);
                if (!folder.exists()) {
                    folder.mkdirs();
                }
                //保存文件
                File saveFile = new File(savePath, saveFileName);
                //复制
                FileUtils.copyInputStreamToFile(file.getInputStream(), saveFile);
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 文件夹下载文件
     *
     * @param originalFileName 文件原名称
     * @param saveFileName     文件保存名称
     * @return com.kmvc.vcbase.model.Result
     * @author cp
     * @date 2022/1/25 9:58
     **/
    @GetMapping(value = "folderDownload")
    @ApiOperation("文件夹下载文件")
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result folderDownload(String originalFileName, String saveFileName, HttpServletRequest request, HttpServletResponse response) {
        Result result = new Result();
        //校验文件数组是否为空
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        try {
            if (redisDao.existsKey(token)) {
                userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
                //参数校验
                if (null == originalFileName || "".equals(originalFileName) || null == saveFileName || "".equals(saveFileName)) {
                    throw new Exception("参数校验不通过");
                }
                // 以流的形式下载文件。
                InputStream fis = new BufferedInputStream(new FileInputStream(FILE_PATH.concat(saveFileName)));
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(originalFileName, "UTF-8"));
                response.setContentType("application/octet-stream");
                response.setCharacterEncoding("UTF-8");
                IOUtils.copy(fis, response.getOutputStream());
                return null;
            } else {
                result.setCode(-1);
                result.setMsg("登录超时");
                return result;
            }
        } catch (Exception e) {
            result.setCode(-1);
            result.setMsg("发生错误:" + e.getMessage());
            return result;
        } finally {
            Result logResult = new Result();
            //日志结果只做标识，不记录返回数据
            BeanUtils.copyProperties(result, logResult);
            logResult.setData(null);
            String resultCode = logResult.getCode() == 0 ? "SUCCESS" : "ERROR";
            logService.logAdd("", "文件夹下载文件", resultCode, logResult.toString(), userInfo, request);
        }
    }

    /**
     * ftp文件上传
     *
     * @param fileArr
     * @return com.kmvc.vcbase.model.Result
     * @author cp
     * @date 2022/1/25 13:49
     **/
    @PostMapping("ftpUpload")
    @ApiOperation("ftp文件上传")
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result ftpUpload(MultipartFile[] fileArr, HttpServletRequest request) {
        Result result = new Result();
        //校验文件数组是否为空
        if (null == fileArr || fileArr.length == 0) {
            result.setCode(ResultEnum.FORBIDDEN.getCode());
            result.setMsg("上传文件列表为空，请核实后重试！");
            return result;
        }
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        FTPClient ftp = new FTPClient();
        try {
            if (redisDao.existsKey(token)) {
                userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
                //判断上传的文件是否合法
                List<String> illegalFileList = new ArrayList<>();
                List<String> failFileList = new ArrayList<>();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                List<Map<String, Object>> fileList = new ArrayList<>(fileArr.length);
                Map<String, Object> map;
                for (MultipartFile file : fileArr) {
                    String orgFileName = file.getOriginalFilename();
                    String uuidFileName = getUuidFileName(orgFileName);
                    String saveFileName = sdf.format(new Date()) + "/" + uuidFileName;
                    //判断文件名是否为空以及后缀名是否合法
                    if (null == orgFileName || "".equals(orgFileName) || !FILE_TYPE.contains(getExtName(orgFileName))) {
                        illegalFileList.add(orgFileName);
                        continue;
                    }
                    // 连接FTP服务器
                    ftp = this.ftpConnection(ftpUrl, ftpPort, ftpUserName, ftpPassword);
                    if (null == ftp) {
                        result.setCode(-1);
                        result.setMsg("连接FTP服务失败！");
                        return result;
                    }
                    //切换FTP目录
                    ftp.makeDirectory(sdf.format(new Date()));
                    boolean cwd = ftp.changeWorkingDirectory(sdf.format(new Date()));
                    if (!cwd) {
                        result.setCode(-1);
                        result.setMsg("FTP切换工作目录失败！");
                        return result;
                    }
                    InputStream in = file.getInputStream();
                    boolean b = ftp.storeFile(uuidFileName, in);
                    if (!b) {
                        failFileList.add(orgFileName);
                        continue;
                    }
                    in.close();
                    ftp.logout();
                    map = new HashMap<>(3);
                    //文件原名称
                    map.put("originalFileName", orgFileName);
                    //文件的存储名称
                    map.put("saveFileName", saveFileName);
                    fileList.add(map);
                }
                if (illegalFileList.size() > 0 || failFileList.size() > 0) {
                    StringBuilder msg = new StringBuilder("下列文件未上传成功：");
                    if (illegalFileList.size() > 0) {
                        msg.append("{[失败原因：文件名不合法]").append(JSON.toJSONString(illegalFileList)).append("};");
                    }
                    if (failFileList.size() > 0) {
                        msg.append("{[失败原因：上传文件发生错误]").append(JSON.toJSONString(failFileList)).append("};");
                    }
                    result.setCode(-1);
                    result.setMsg(msg.toString());
                    return result;
                }
                result.setCode(0);
                result.setMsg("上传成功");
                result.setData(fileList);
            } else {
                result.setCode(-1);
                result.setMsg("登录超时");
            }
            return result;
        } catch (Exception e) {
            result.setCode(-1);
            result.setMsg("发生错误:" + e.getMessage());
            return result;
        } finally {
            if (null != ftp && ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ignored) {
                }
            }
            Result logResult = new Result();
            //日志结果只做标识，不记录返回数据
            BeanUtils.copyProperties(result, logResult);
            logResult.setData(null);
            String resultCode = logResult.getCode() == 0 ? "SUCCESS" : "ERROR";
            logService.logAdd("", "minio文件上传", resultCode, logResult.toString(), userInfo, request);
        }
    }

    /**
     * ftp文件上传(支持uniapp批量上传,文件的键不可以能相同，否之不能取到全部文件)
     *
     * @return com.kmvc.vcbase.model.Result
     * @author cp
     * @date 2022/1/25 13:49
     **/
    @PostMapping("ftpMultiUpload")
    @ApiOperation("ftp文件上传")
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result ftpMultiUpload(HttpServletRequest request) {
        Result result = new Result();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> multipartFileMap = multipartRequest.getFileMap();
        List<MultipartFile> fileArr = new ArrayList<MultipartFile>(multipartFileMap.values());
        //校验文件数组是否为空
        if (null == fileArr || fileArr.size() == 0) {
            result.setCode(ResultEnum.FORBIDDEN.getCode());
            result.setMsg("上传文件列表为空，请核实后重试！");
            return result;
        }
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        FTPClient ftp = new FTPClient();
        try {
            if (redisDao.existsKey(token)) {
                userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
                //判断上传的文件是否合法
                List<String> illegalFileList = new ArrayList<>();
                List<String> failFileList = new ArrayList<>();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                List<Map<String, Object>> fileList = new ArrayList<>(fileArr.size());
                Map<String, Object> map;
                for (MultipartFile file : fileArr) {
                    String orgFileName = file.getOriginalFilename();
                    String uuidFileName = getUuidFileName(orgFileName);
                    String saveFileName = sdf.format(new Date()) + "/" + uuidFileName;
                    //判断文件名是否为空以及后缀名是否合法
                    if (null == orgFileName || "".equals(orgFileName) || !FILE_TYPE.contains(getExtName(orgFileName))) {
                        illegalFileList.add(orgFileName);
                        continue;
                    }
                    // 连接FTP服务器
                    ftp = this.ftpConnection(ftpUrl, ftpPort, ftpUserName, ftpPassword);
                    if (null == ftp) {
                        result.setCode(-1);
                        result.setMsg("连接FTP服务失败！");
                        return result;
                    }
                    //切换FTP目录
                    ftp.makeDirectory(sdf.format(new Date()));
                    boolean cwd = ftp.changeWorkingDirectory(sdf.format(new Date()));
                    if (!cwd) {
                        result.setCode(-1);
                        result.setMsg("FTP切换工作目录失败！");
                        return result;
                    }
                    InputStream in = file.getInputStream();
                    boolean b = ftp.storeFile(uuidFileName, in);
                    if (!b) {
                        failFileList.add(orgFileName);
                        continue;
                    }
                    in.close();
                    ftp.logout();
                    map = new HashMap<>(3);
                    //文件原名称
                    map.put("originalFileName", orgFileName);
                    //文件的存储名称
                    map.put("saveFileName", saveFileName);
                    fileList.add(map);
                }
                if (illegalFileList.size() > 0 || failFileList.size() > 0) {
                    StringBuilder msg = new StringBuilder("下列文件未上传成功：");
                    if (illegalFileList.size() > 0) {
                        msg.append("{[失败原因：文件名不合法]").append(JSON.toJSONString(illegalFileList)).append("};");
                    }
                    if (failFileList.size() > 0) {
                        msg.append("{[失败原因：上传文件发生错误]").append(JSON.toJSONString(failFileList)).append("};");
                    }
                    result.setCode(-1);
                    result.setMsg(msg.toString());
                    return result;
                }
                result.setCode(0);
                result.setMsg("上传成功");
                result.setData(fileList);
            } else {
                result.setCode(-1);
                result.setMsg("登录超时");
            }
            return result;
        } catch (Exception e) {
            result.setCode(-1);
            result.setMsg("发生错误:" + e.getMessage());
            return result;
        } finally {
            if (null != ftp && ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ignored) {
                }
            }
            Result logResult = new Result();
            //日志结果只做标识，不记录返回数据
            BeanUtils.copyProperties(result, logResult);
            logResult.setData(null);
            String resultCode = logResult.getCode() == 0 ? "SUCCESS" : "ERROR";
            logService.logAdd("", "minio文件上传", resultCode, logResult.toString(), userInfo, request);
        }
    }

    public boolean ftpUpload1(MultipartFile[] fileArr, UserInfo userInfo,String uuid) {
        FTPClient ftp = new FTPClient();
        try {
            //判断上传的文件是否合法
            List<String> illegalFileList = new ArrayList<>();
            List<String> failFileList = new ArrayList<>();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            List<Map<String, Object>> fileList = new ArrayList<>(fileArr.length);
            Map<String, Object> map;
            for (MultipartFile file : fileArr) {
                String orgFileName = file.getOriginalFilename();
                String uuidName = uuid + "." + getExtName(file.getOriginalFilename());
                String saveFileName = sdf.format(new Date()) + "/" + uuid + "." + getExtName(file.getOriginalFilename());
                //判断文件名是否为空以及后缀名是否合法
                if (null == orgFileName || "".equals(orgFileName) || !FILE_TYPE.contains(getExtName(orgFileName))) {
                    illegalFileList.add(orgFileName);
                    continue;
                }
                // 连接FTP服务器
                ftp = this.ftpConnection(ftpUrl, ftpPort, ftpUserName, ftpPassword);
                if (null == ftp) {
                    return false;
                }
                //切换FTP目录
                ftp.makeDirectory(sdf.format(new Date()));
                boolean cwd = ftp.changeWorkingDirectory(sdf.format(new Date()));
                if (!cwd) {
                    return false;
                }
                InputStream in = file.getInputStream();
                boolean b = ftp.storeFile(uuidName, in);
                if (!b) {
                    failFileList.add(orgFileName);
                    continue;
                }
                in.close();
                ftp.logout();
                map = new HashMap<>(3);
                //文件原名称
                map.put("originalFileName", orgFileName);
                //文件的存储名称
                map.put("saveFileName", saveFileName);
                fileList.add(map);
            }
            if (illegalFileList.size() > 0 || failFileList.size() > 0) {
                StringBuilder msg = new StringBuilder("下列文件未上传成功：");
                if (illegalFileList.size() > 0) {
                    msg.append("{[失败原因：文件名不合法]").append(JSON.toJSONString(illegalFileList)).append("};");
                }
                if (failFileList.size() > 0) {
                    msg.append("{[失败原因：上传文件发生错误]").append(JSON.toJSONString(failFileList)).append("};");
                }
                return false;
            }
            return true;
        } catch (Exception e) {
            return false;
        } finally {
            if (null != ftp && ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ignored) {
                }
            }
        }
    }

    /**
     * ftp下载文件
     *
     * @param originalFileName 文件原名称
     * @param saveFileName     文件保存名称
     * @return com.kmvc.vcbase.model.Result
     * @author cp
     * @date 2022/1/25 9:58
     **/
    @GetMapping(value = "ftpDownload")
    @ApiOperation("ftp下载文件")
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result ftpDownload(String originalFileName, String saveFileName, HttpServletRequest request, HttpServletResponse response) {
        Result result = new Result();
        //校验文件数组是否为空
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        FTPClient ftp = new FTPClient();
        try {
            if (redisDao.existsKey(token)) {
                userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
                //参数校验
                if (null == originalFileName || "".equals(originalFileName) || null == saveFileName || "".equals(saveFileName)) {
                    throw new Exception("参数校验不通过");
                }
                // 连接FTP服务器
                ftp = this.ftpConnection(ftpUrl, ftpPort, ftpUserName, ftpPassword);
                if (null == ftp) {
                    result.setCode(-1);
                    result.setMsg("连接FTP服务失败！");
                    return result;
                }
                String cwdUrl = saveFileName.substring(0, saveFileName.lastIndexOf("/"));
                String ftpFileName = saveFileName.substring(saveFileName.lastIndexOf("/") + 1);
                boolean b = ftp.changeWorkingDirectory(cwdUrl);
                if (!b) {
                    result.setCode(-1);
                    result.setMsg("切换FTP工作目录失败！");
                    return result;
                }
                FTPFile[] ftpFiles = ftp.listFiles();
                InputStream fis = null;
                for (FTPFile ff : ftpFiles) {
                    if (ftpFileName.equalsIgnoreCase(ff.getName())) {
                        fis = ftp.retrieveFileStream(new String(ff.getName().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
                    }
                }
                if (null == fis) {
                    result.setCode(-1);
                    result.setMsg("未找到文件！");
                    return result;
                }
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(originalFileName, "UTF-8"));
                response.setContentType("application/octet-stream");
                response.setCharacterEncoding("UTF-8");
                IOUtils.copy(fis, response.getOutputStream());
                return null;
            } else {
                result.setCode(-1);
                result.setMsg("登录超时");
                return result;
            }
        } catch (Exception e) {
            result.setCode(-1);
            result.setMsg("发生错误:" + e.getMessage());
            return result;
        } finally {
            if (null != ftp && ftp.isConnected()) {
                try {
                    ftp.logout();
                } catch (IOException ignored) {
                }
            }
            Result logResult = new Result();
            //日志结果只做标识，不记录返回数据
            BeanUtils.copyProperties(result, logResult);
            logResult.setData(null);
            String resultCode = logResult.getCode() == 0 ? "SUCCESS" : "ERROR";
            logService.logAdd("", "minio文件上传", resultCode, logResult.toString(), userInfo, request);
        }
    }


    /**
     * 连接ftp服务器
     *
     * @param ip       ftp地址
     * @param port     端口
     * @param username 账号
     * @param password 密码
     * @return org.apache.commons.net.ftp.FTPClient
     * @author cp
     * @date 2022/1/25 15:00
     **/
    private FTPClient ftpConnection(String ip, String port, String username, String password) {
        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient.connect(ip, Integer.parseInt(port));
            ftpClient.login(username, password);
            ftpClient.setControlEncoding("GBK");
            //是否成功登录服务器
            int replyCode = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                ftpClient.disconnect();
                return null;
            }
            //这句最好加告诉对面服务器开一个端口
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.setFileTransferMode(FTPClient.STREAM_TRANSFER_MODE);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return ftpClient;
    }


    /**
     * 把文件名转换成uuid表示，防止文件名上传重复
     *
     * @param fileName 文件名称
     * @return java.lang.String
     * @author cp
     * @date 2022/1/21 10:08
     **/
    private String getUuidFileName(String fileName) {
//        UUID uuid = UUID.randomUUID();
        long l = System.currentTimeMillis();
        return fileName+"_"+l + "." + this.getExtName(fileName);
    }

    /**
     * 获取文件后缀名
     *
     * @param fileName 文件名
     * @return java.lang.String
     * @author cp
     * @date 2022/1/21 10:08
     **/
    private String getExtName(String fileName) {
        int i = fileName.lastIndexOf('.');
        int leg = fileName.length();
        return i > 0 ? (i + 1) == leg ? " " : fileName.substring(i + 1) : " ";
    }

    /**
     * 文件上传
     *
     * @param file       文件
     * @param fileName   文件名称
     * @param bucketName 存储桶名称
     * @return java.lang.Boolean
     * @author cp
     * @date 2022/1/21 9:57
     **/
    public Boolean upload(MultipartFile file, String fileName, String bucketName) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String fileName1 =  sdf.format(new Date()) + "/" + fileName +  "." + getExtName(file.getOriginalFilename());
            PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(bucketName).object(fileName1)
                    .stream(file.getInputStream(), file.getSize(), -1).contentType(file.getContentType()).build();
            //文件名称相同会覆盖
            minioClient.putObject(objectArgs);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 文件下载
     *
     * @param bucketName       存储bucket名称
     * @param saveFileName     保存的文件名称
     * @param originalFileName 原始文件名
     * @param res              response
     */
    public void download(String bucketName, String saveFileName, String originalFileName, HttpServletResponse res) {
        GetObjectArgs objectArgs = GetObjectArgs.builder().bucket(bucketName)
                .object(saveFileName).build();
        try (GetObjectResponse response = minioClient.getObject(objectArgs)) {
            byte[] buf = new byte[1024];
            int len;
            try (FastByteArrayOutputStream os = new FastByteArrayOutputStream()) {
                while ((len = response.read(buf)) != -1) {
                    os.write(buf, 0, len);
                }
                os.flush();
                byte[] bytes = os.toByteArray();
                res.setCharacterEncoding("utf-8");
                //设置强制下载不打开
//                res.setContentType("application/force-download");
//                res.addHeader("Content-Disposition", "attachment;fileName=" + originalFileName);
                res.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
                res.setHeader("Content-disposition", "attachment; filename=" + originalFileName);
                res.getOutputStream().write(bytes);
                res.flushBuffer();
                res.getOutputStream().close();
//                try (ServletOutputStream stream = res.getOutputStream()) {
//                    stream.write(bytes);
//                    stream.flush();
//                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取文件流
     *
     * @param bucketName 存储桶名称
     * @param objectKey  文件key
     * @return java.io.InputStream  文件流
     * @author cp
     * @date 2022/1/21 10:26
     **/
    public InputStream download(String bucketName, String objectKey) throws Exception {
        return minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectKey).build());
    }

    /**
     * 获取文件签名url
     *
     * @param bucketName 存储桶名称
     * @param objectKey  文件key
     * @param expires    签名有效时间  单位秒 默认是7天，不得大于七天
     * @return java.lang.String     文件签名地址
     * @author cp
     * @date 2022/1/21 10:23
     **/
    public String getSignedUrl(String bucketName, String objectKey, int expires) throws Exception {
        return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder().method(Method.GET).bucket(bucketName).object(objectKey).expiry(expires).build());
    }

    /**
     * 查看文件对象信息
     *
     * @param bucketName 存储桶名称
     * @return java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     * @author cp
     * @date 2022/1/21 10:03
     **/
    public List<Map<String, Object>> listObjects(String bucketName) {
        Iterable<io.minio.Result<Item>> results = minioClient.listObjects(
                ListObjectsArgs.builder().bucket(bucketName).build());
        List<Map<String, Object>> objectItems = new ArrayList<>();
        try {
            for (io.minio.Result<Item> result : results) {
                Item item = result.get();
                Map<String, Object> itemMap = new HashMap<>(2);
                itemMap.put("objectName", item.objectName());
                itemMap.put("size", item.size());
                objectItems.add(itemMap);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return objectItems;
    }


    /**
     * 批量删除文件对象
     *
     * @param bucketName 存储桶名称
     * @param objects    对象名称集合
     * @return java.lang.Iterable<io.minio.Result < io.minio.messages.DeleteError>>
     * @author cp
     * @date 2022/1/21 10:04
     **/
    public Iterable<io.minio.Result<DeleteError>> removeObjects(String bucketName, List<String> objects) {
//        List<DeleteObject> dos = objects.stream().map(DeleteObject::new).collect(Collectors.toList());
//        return minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(bucketName).objects(dos).build());
        List<DeleteObject> deleteObjects = new LinkedList<>();
        if(!objects.isEmpty()){
            for(String item:objects){
                deleteObjects.add(new DeleteObject(item));
            }
            try{
                Iterable<io.minio.Result<DeleteError>> results =
                        minioClient.removeObjects(
                                RemoveObjectsArgs.builder().bucket(bucketName).objects(deleteObjects).build());
                for (io.minio.Result<DeleteError> result1 : results) {
                    DeleteError error = result1.get();
                    System.out.println(
                            "Error in deleting object " + error.objectName() + "; " + error.message());
                }
                return results;
            }
            catch (Exception e){
                e.printStackTrace();
                return null;
            }
        }
        else{
            return null;
        }
    }

    /**
     * 判断存储桶是否存在
     *
     * @param bucketName 存储桶名称
     * @return java.lang.Boolean
     * @author cp
     * @date 2022/1/21 9:50
     **/
    public Boolean bucketExists(String bucketName) {
        boolean isExists;
        try {
            isExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return isExists;
    }

    /**
     * 创建存储桶并设置存储桶策略
     *
     * @param bucketName 存储桶名称
     * @return java.lang.Boolean
     * @author cp
     * @date 2022/1/21 9:53
     **/
    public Boolean makeBucket(String bucketName) {
        try {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 删除存储桶
     *
     * @param bucketName 存储桶名称
     * @return java.lang.Boolean
     * @author cp
     * @date 2022/1/21 9:55
     **/
    public Boolean removeBucket(String bucketName) {
        try {
            minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    /**
     * 设置存储桶策略
     *
     * @param bucketName 存储桶名称
     * @param policy     存储桶策略
     * @author cp
     * @date 2022/1/21 10:19
     **/
    public void setBucketPolicy(String bucketName, String policy) throws Exception {
        switch (policy) {
            case "read-only":
                minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucketName).config(READ_ONLY.replace(BUCKET_PARAM, bucketName)).build());
                break;
            case "write-only":
                minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucketName).config(WRITE_ONLY.replace(BUCKET_PARAM, bucketName)).build());
                break;
            case "read-write":
                minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucketName).config(READ_WRITE.replace(BUCKET_PARAM, bucketName)).build());
                break;
            case "none":
            default:
                break;
        }
    }

    /**
     * 获取文件信息
     *
     * @param bucketName bucket名称
     * @param objectName 文件名称
     * @return io.minio.StatObjectResponse
     * @author cp
     * @date 2022/1/24 16:43
     **/
    public StatObjectResponse getObjectInfo(String bucketName, String objectName) throws Exception {
        StatObjectArgs statObjectArgs = StatObjectArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                .build();
        return minioClient.statObject(statObjectArgs);
    }
    @PostMapping("/getHistoryImportSize")
    @ApiOperation(value = "获取导入文件缓存大小")
    public Result getHistoryImportSize(HttpServletRequest request, HttpServletResponse response) {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        try {
            if (redisDao.existsKey(token)) {
                userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
                String resultDsc="";
                Map<String,Object> map=new HashMap<>();
                map.put("daysBefore",daysBefore);
                long fileSize=fileService.getHistoryImportSize(map);
                Map<String,Object> resultMap=new HashMap<>();
                String formatSize="";
                //大于1M使用MB显示
                if(fileSize>1024){
                    formatSize=(fileSize/1204)+"MB";
                }
                else{
                    formatSize=fileSize+"KB";
                }
                resultMap.put("size",formatSize);
                resultMap.put("days",daysBefore);
                result.setMsg("获取成功");
                result.setData(resultMap);
                Result logResult = new Result();
                logResult.setCode(0);
                //不记录返回数据，只做标识
                logResult.setMsg("获取成功");
                logResult.setServerID(result.getServerID());
                logService.logAdd("{}", "获取导入文件缓存大小", "SUCCESS", logResult.toString(), userInfo, request);
            } else {
                result.setCode(-1);
                result.setMsg("登录超时");
                logService.logAdd("{}", "获取导入文件缓存大小", "ERROR", result.toString(), userInfo, request);
            }
        } catch (Exception e) {
            System.out.println("e = " + e.getMessage().toString());
            result.setCode(ResultEnum.NODATE.getCode());
            result.setMsg("出现错误！");
            return result;
        }
        return result;
    }
    @PostMapping("/clearImportFile")
    @ApiOperation(value = "清除导入文件缓存")
    public Result clearUploadFile(HttpServletRequest request, HttpServletResponse response) {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        try {
            if (redisDao.existsKey(token)) {
                userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
                String resultDsc="";
                Map<String,Object> map=new HashMap<>();
                map.put("daysBefore",daysBefore);
                List<String> fileList=fileService.getHistoryImportFile(map);
                if(!fileList.isEmpty()){
                    if("file".equals(importSaveType)){
                        String fullPath="";
                        for(String item:fileList){
                            fullPath=importSavePath+item;
                            File file=new File(fullPath);
                            file.delete();
                        }
                        fileService.updateImportInfo(map);
                    }
                    else if("ftp".equals(importSaveType)){
                        FTPClient ftp = this.ftpConnection(ftpUrl, ftpPort, ftpUserName, ftpPassword);
                        String fullPath="";
                        for(String item:fileList){
                            fullPath=importSavePath+item;
                            ftp.deleteFile(fullPath);
                        }
                        fileService.updateImportInfo(map);
                    }
                    else if("minio".equals(importSaveType)){
                        Iterable<io.minio.Result<DeleteError>> results=this.removeObjects(importSavePath,fileList);
                        fileService.updateImportInfo(map);
                    }
                }
                result.setMsg("操作成功");
//                    result.setData(reMap);
                Result logResult = new Result();
                logResult.setCode(0);
                //不记录返回数据，只做标识
                logResult.setMsg("操作成功");
                logResult.setServerID(result.getServerID());
                logService.logAdd("{}", "清除导入文件缓存", "SUCCESS", logResult.toString(), userInfo, request);
            } else {
                result.setCode(-1);
                result.setMsg("登录超时");
                logService.logAdd("{}", "清除导入文件缓存", "ERROR", result.toString(), userInfo, request);
            }
        } catch (Exception e) {
            System.out.println("e = " + e.getMessage().toString());
            result.setCode(ResultEnum.NODATE.getCode());
            result.setMsg("出现错误！");
            return result;
        }
        return result;
    }

}
